from docx import Document
from docx.shared import Inches, Pt
from docx.enum.text import WD_ALIGN_PARAGRAPH
import re

# 读取Markdown文件
def read_md_file(file_path):
    with open(file_path, 'r', encoding='utf-8') as f:
        return f.readlines()

# 将Markdown转换为DOC
def convert_md_to_doc(md_lines, docx_path):
    doc = Document()
    
    # 设置文档样式
    style = doc.styles['Normal']
    font = style.font
    font.name = '微软雅黑'
    font.size = Pt(10.5)
    
    # 跟踪当前段落类型
    current_heading_level = 0
    current_table = None
    in_table_header = False
    
    for line in md_lines:
        line = line.rstrip('\n')
        
        # 跳过空行
        if not line.strip():
            if current_table is None:
                doc.add_paragraph()
            continue
        
        # 处理标题
        heading_match = re.match(r'^(#{1,6})\s+(.*)$', line)
        if heading_match:
            level = len(heading_match.group(1))
            text = heading_match.group(2)
            
            if level == 1:
                # 一级标题
                paragraph = doc.add_heading(text, level=0)
                paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER
                
            elif level == 2:
                # 二级标题
                doc.add_heading(text, level=1)
                
            elif level == 3:
                # 三级标题
                doc.add_heading(text, level=2)
                
            elif level == 4:
                # 四级标题
                doc.add_heading(text, level=3)
            
            current_heading_level = level
            current_table = None
            continue
        
        # 处理表格行
        if line.startswith('|') and '|' in line:
            # 检查是否是表格分隔行
            if re.match(r'^\|\s*:?---+\s*\|', line):
                in_table_header = False
                continue
            
            # 提取表格单元格，正确处理所有单元格（包括空单元格）
            # 去掉第一个和最后一个元素（因为它们通常是空的），然后保留所有单元格
            split_cells = line.split('|')
            cells = split_cells[1:-1]  # 去掉第一个和最后一个空元素
            
            if current_table is None:
                # 创建新表格
                current_table = doc.add_table(rows=1, cols=len(cells))
                current_table.style = 'Table Grid'
                hdr_cells = current_table.rows[0].cells
                for i, cell in enumerate(cells):
                    # 去除多余的前导和尾随空格，但保留内部空格
                    hdr_cells[i].text = cell.strip()
                    # 设置表头格式
                    hdr_cells[i].paragraphs[0].runs[0].bold = True
                in_table_header = True
            else:
                # 添加表格行
                row_cells = current_table.add_row().cells
                for i, cell in enumerate(cells):
                    if i < len(row_cells):
                        # 去除多余的前导和尾随空格，但保留内部空格
                        row_cells[i].text = cell.strip()
            
            continue
        
        # 处理代码块（简单处理，作为普通文本）
        if line.startswith('```'):
            continue
        
        # 处理加粗文本
        if '**' in line:
            paragraph = doc.add_paragraph()
            parts = re.split(r'(\*\*[^\*]+\*\*)', line)
            for part in parts:
                if part.startswith('**') and part.endswith('**'):
                    run = paragraph.add_run(part[2:-2])
                    run.bold = True
                else:
                    paragraph.add_run(part)
        else:
            # 普通文本段落
            doc.add_paragraph(line)
    
    # 保存文档
    doc.save(docx_path)
    print(f"DOC文档已保存为: {docx_path}")

import sys

# 主函数
def main():
    # 支持命令行参数，默认使用数据库设计文档.md
    md_file = sys.argv[1] if len(sys.argv) > 1 else '数据库设计文档.md'
    
    # 根据Markdown文件名生成DOCX文件名
    docx_file = md_file.replace('.md', '.docx')
    
    try:
        print(f"正在读取Markdown文件: {md_file}...")
        md_lines = read_md_file(md_file)
        
        print("正在转换为DOC格式...")
        convert_md_to_doc(md_lines, docx_file)
        
        print(f"转换完成！文档已保存为: {docx_file}")
        
    except Exception as e:
        print(f"发生错误: {e}")
        print("请先安装python-docx库: pip install python-docx")

if __name__ == "__main__":
    main()